import string
import random
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

def generate_captcha_text(length=6):
    # 生成包含大写和小写字母的验证码文本
    characters = string.ascii_letters + string.digits  # 包含大小写字母和数字
    return ''.join(random.choices(characters, k=length))

def create_captcha_image(text, image_size, font_size):
    # 创建一个新的空白图像
    image = Image.new('RGB', size=image_size, color=(255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 使用系统字体（假设你选择的字体在系统中可用）
    # fonts = ImageFont.load_default()
    # 或者加载一个特殊的字体文件
    print(Path(__file__).resolve().parent.parent)
    font_path = f"{Path(__file__).resolve().parent.parent}\\static\\fonts\\Arial.ttf"

    font = ImageFont.truetype(font=font_path, size=font_size)

    # 绘制验证码文本
    draw.text((15, 7), text, font=font, fill=(0, 0, 0))

    # 添加一些噪点
    for i in range(2000):
        draw.point((random.randint(0, 200), random.randint(0, 50)),
                   fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

    # 添加干扰线条
    for _ in range(2):  # 随机添加5条线条
        start_pos = (random.randint(0, image_size[0]), random.randint(0, image_size[1]))
        end_pos = (random.randint(0, image_size[0]), random.randint(0, image_size[1]))
        draw.line([start_pos, end_pos],
                  fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=2)

    return image

if __name__ == "__main__":
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
    captcha_image = create_captcha_image(captcha_text, (120, 35), 22)
    captcha_image.show()  # 显示生成的验证码图像
    captcha_image.save('captcha.png')  # 保存图像文件